import { useEffect, useState } from 'react'
import { Image, Ellipsis, NavBar, Skeleton, Button, Popover, Dialog } from 'antd-mobile'
import styles from "./index.module.less"
import HeaderNav from "@/components/header-nav"
import FooterNav from "@/components/footer-nav"
import { useSearchParams } from 'react-router-dom'
import { MoreOutline } from 'antd-mobile-icons'
import { showSuccessToast } from '@/utils/customToast';
const { getUserWorldBookDetails, createChat, deleteRole } = $globalServicer('world')

const ItemCrad = (props) => {
  const customNavigate = $globalNavigate()
  const [params] = useSearchParams();
  const [loading, setLoading] = useState(true)
  console.log("🚀 ~ ItemCrad ~ params:", params)
  const id = params.get('id');
  const [worldInfo, setWorldInfo] = useState(null)
  useEffect(() => {
    getUserWorldBookDetails(id).then(res => {
      setWorldInfo(res)
    });
  }, [])
  const handleOperate = (node, item) => {
    console.log('handleOperate', node)
    console.log('handleOperate', item)
    if (node.key === 'delete') {
      Dialog.confirm({
        content: '是否确认删除该角色？',
        cancelText:
          <div className={styles.cancelClass}>
            取消
          </div>,
        confirmText: <div className={styles.confirmClass}>确认</div>,
        onConfirm: async () => {
          await deleteRole({ id: item.id }).then(res => {
            showSuccessToast('删除成功');
            customNavigate('/world')
          })
        },
      })
    } else if (node.key === 'edit') {
      // 编辑角色 id  是 user_world_id role_id 是编辑角色的id
      customNavigate(`/world/createMixRoleWorld?id=${id}&roleId=${item.id}&type=edit`)
    }
  }
  const handleTagClick = (item) => {
    console.log("🚀 ~ handleTagClick ~ item:", item)
    if (item.chat_group_id === 0) {
      const data = {
        type: 1, // 1 角色聊天 2 世界聊天
        roles: [
          item.id
        ]
      }
      createChat(data).then(res => {
        customNavigate('/chatlist')
        // customNavigate(`/chatDetail?type=1&chatId=${res.chat_id}&name=${name}&userWorldId=${user_world_id}`)
      })
    } else {
      customNavigate('/chatlist')
      // TODO: 这里直接调用角色的 st_chat_id
      // customNavigate(`/chatDetail?type=1&chatId=${st_chat_id}&name=${name}&userWorldId=${user_world_id}`)
    }
  }
  const actions = [
    {
      key: 'edit',
      text: '编辑',
      path: 'editGroupChat',
    },
    {
      key: 'delete',
      text: '删除',
      path: 'deleteGroupChat',
    },
  ]
  return (
    <div className={styles.detail_warp}>
      <div className={styles.headerTop}
        style={{ backgroundImage: `url(${worldInfo?.world_cover})`, backgroundSize: 'cover' }}
      >
        <div className="header">
          <HeaderNav backArrow={true} title={worldInfo?.world_name} styleObj={{ color: '#fff' }}>
          </HeaderNav>
        </div>
        <div className={styles.desc}>
          {
            worldInfo?.description
          }
        </div>
      </div>
      <div className={styles.descWrapper}>
        <div className={styles.classifyListWrapper}>
          <p className={styles.classifyTitle}>
            主要角色介绍
          </p>
          <div className={styles.personList}>
            {
              worldInfo?.roles?.filter(item => item.is_main)?.map((item, index) =>
                <div className={styles.roleItem} key={item.id}>
                  <div className={styles.itemTop}>
                    <div className={styles.itemLeft}>
                      <img src={item.cover} alt="" />
                      <span className={styles.itemName}>{item.name}</span>
                    </div>
                    <div className={styles.itemRight}>
                      <span className={styles.more}>
                        <Popover.Menu
                          actions={actions}
                          placement='bottom-start'
                          onAction={node => handleOperate(node, item)}
                          trigger='click'
                        >
                          <MoreOutline color='#898989' />
                        </Popover.Menu>
                      </span>
                      <Button
                        shape="rounded"
                        fill="outline"
                        className={`${styles.tag} ${styles.selected}`}
                        onClick={() => handleTagClick(item)}
                      >
                        聊天
                      </Button>
                    </div>
                  </div>
                </div>
              )
            }
          </div>
          <div className={styles.groupChatList}>
            {
              worldInfo?.roles?.filter(item => !item.is_main).map((item, index) => (<div className={styles.groupChatItem} key={item.id}>
                <img src={item.cover} alt="" />
                <p className={styles.groupChatItemName}>{item.name}</p>
              </div>))
            }
          </div>
        </div>
      </div>
      <div className="footer">
        <FooterNav></FooterNav>
      </div>
    </div>
  );
};

export default ItemCrad;
